from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils import error, success, FileHandler

upload_api = Blueprint('upload_api', __name__, url_prefix='/api/upload')

@upload_api.route('/image', methods=['POST'])
@jwt_required()
def upload_image():
    """上传图片文件"""
    try:
        if 'file' not in request.files:
            return error(code=400, msg='没有选择文件').to_response()
        
        file = request.files['file']
        if file.filename == '':
            return error(code=400, msg='没有选择文件').to_response()
        
        # 验证文件
        is_valid, error_msg = FileHandler.validate_image_file(file)
        if not is_valid:
            return error(code=400, msg=error_msg).to_response()
        
        # 保存文件
        result = FileHandler.save_file(file, 'image')
        
        if result['success']:
            return success(data={
                'filename': result['filename'],
                'original_filename': result['original_filename'],
                'file_url': FileHandler.get_file_url(result['relative_path']),
                'file_size': result['file_size'],
                'file_type': result['file_type']
            }, msg='图片上传成功').to_response()
        else:
            return error(code=400, msg=result['error']).to_response()
            
    except Exception as e:
        return error(code=500, msg=f'图片上传失败: {str(e)}').to_response()

